package com.ctgu.juc_project.example.start;

import com.ctgu.juc_project.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerArray;


@Slf4j
@ThreadSafe
public class SafeArray {

    private static int threadCount = 10;
    private static CountDownLatch countDown = new CountDownLatch(threadCount);
    private static int[] values = new int[10];
    private static AtomicIntegerArray atomicValues = new AtomicIntegerArray(values);

    private static void add(){
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < values.length; j++) {
                atomicValues.incrementAndGet(j);
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        countDown.countDown();
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < threadCount; i++) {
            new Thread(SafeArray::add).start();
        }
        countDown.await();
        log.info("atomicValues: {}", atomicValues);
        log.info("values: {}", values);
    }
}
